<?php

namespace App\Http\Controllers\OpenShop\Feishu;

use App\Http\Controllers\BaseController;
use App\Http\Middleware\OpenShop\AppletAuth;
use App\Models\Common\ConfigModel;
use App\Service\OpenShop\Feishu\AppletLoginService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AppletLoginController extends BaseController
{
    public function login(Request $request)
    {
        $appid = $request->header('appid', '');

        $this->validate($request, [
            'code'  => 'required|string',
        ]);

        try {
            $fsConfig     = ConfigModel::getFsConfigByAppId($appid);
            $appid        = $fsConfig['appId'];
            $appSecret    = $fsConfig['appSecret'];
            $platformName = $fsConfig['platformName'];

            $appletConfig = [
                "platformName" => $platformName,
                'appId'        => $appid,
                'appSecret'    => $appSecret,
                'ext'          => 604800,
                'inv'          => 604800
            ];

            $arr = AppletLoginService::loginByFeishuCode($request->code, $appletConfig, $request->ip());
        } catch (\Exception $exception) {
            Log::warning($exception);
            return $this->fail(110, '暂无夸父选址权限。如需使用，请在 飞书-工作台-审批-搜索"数字"，点击【数字账号系统申请】-选择夸父选址系统，进行权限申请。');
        }

        return $this->success(['token' => $arr['token']]);
    }
}
